package com.example.client.service.impl;


import com.example.client.Security.LoginUserDetails;
import com.example.client.Utiles.JWTUtiles;
import com.example.client.domain.User;
import com.example.client.mapper.UserMapper;
import com.example.client.pojo.Code;
import com.example.client.pojo.Result;
import com.example.client.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public Result<Map> login(String username, String password) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null) {
            return new Result(Code.RESPONSE_CODE_FAIL, "登录失败");
        }
        LoginUserDetails principal = (LoginUserDetails) authenticate.getPrincipal();
        User user = principal.getUser();


        Map<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        String token = JWTUtiles.getToken(map);

        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("token", token);
        return new Result<Map>(dataMap, Code.RESPONSE_CODE_SUCCESS, "登录成功");
    }
}
